﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

/**************************
 * NOTE: This code was taken straight from the MSDN Article on MD5:
 * ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/49f8a9c7-7c97-aacf-80c1-196d4b112529.htm
 **************************/

namespace P3SS.Security
{
	/// <summary>
	/// A static wrapper for .NET's MD5 classes
	/// </summary>
	public static class MD5Handler
	{
		/// <summary>
		/// Hashes a given string using MD5 and outputs a 32 character hex representation of the hash
		/// </summary>
		/// <param name="input">String to hash using MD5</param>
		/// <returns>A 32 hex character string which is the hash</returns>
		public static string getMd5Hash(string input)
		{
			// Create a new instance of the MD5CryptoServiceProvider object.
			MD5 md5Hasher = MD5.Create();

			// Convert the input string to a byte array and compute the hash.
			byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

			// Create a new Stringbuilder to collect the bytes
			// and create a string.
			StringBuilder sBuilder = new StringBuilder();

			// Loop through each byte of the hashed data 
			// and format each one as a hexadecimal string.
			for (int i = 0; i < data.Length; i++)
			{
				sBuilder.Append(data[i].ToString("x2"));
			}

			// Return the hexadecimal string.
			return sBuilder.ToString();
		}

		/// <summary>
		/// Verifies the hash of the given input with a given hash
		/// </summary>
		/// <param name="input">Input to hash and compare</param>
		/// <param name="hash">Hash to compare</param>
		/// <returns>True if the input's hash is the same value as the given hash, otherwise false</returns>
		public static bool verifyMd5Hash(string input, string hash)
		{
			// Hash the input.
			string hashOfInput = getMd5Hash(input);

			// Create a StringComparer an comare the hashes.
			StringComparer comparer = StringComparer.OrdinalIgnoreCase;

			if (0 == comparer.Compare(hashOfInput, hash))
			{
				return true;
			}
			else
			{
				return false;
			}
		}

	}
}
